package xyc.sjxy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CORSFilter implements Filter {

    public void init(FilterConfig fConfig) throws ServletException {
        // 初始化操作，如果有的话
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 设置允许跨域的源
        httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
        // 允许的请求方法
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS,PATCH");
        // 允许的请求头
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        // 是否允许携带cookie
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        // 预检请求的有效期，单位为秒。这里设置为一天
        httpResponse.setHeader("Access-Control-Max-Age", "86400");
        // 处理预检请求（OPTIONS请求）
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {
        // 清理资源，如果有的话
    }
}

